import React, { useEffect, useRef, useState } from 'react';
import { cate } from '../../https/index';
import { SideBar } from 'antd-mobile';
import { useThrottleFn } from 'ahooks';
import '../../App.css';
import { useNavigate } from 'react-router-dom';

export default function Filters() {
  const [items, setItems] = useState(JSON.parse(sessionStorage.getItem('items')) || []);
  const [activeKey, setActiveKey] = useState('');
  const mainElementRef = useRef(null);
  const itemRefs = useRef({});
  const HEADER_HEIGHT = 50;
  const scrollingRef = useRef(false); // 防止滚动冲突
  const navigate = useNavigate();

  const getCate = async () => {
    try {
      const res = await cate();
      setItems(res.data.categories);
      setActiveKey(res.data.categories[0]._id);
      sessionStorage.setItem('items', JSON.stringify(res.data.categories));
    } catch (error) {
      console.error('Failed to fetch categories:', error);
    }
  };

  useEffect(() => {
    getCate();
  }, []);

  // 平滑滚动到指定元素
  const scrollToElement = (element) => {
    if (!element) return;

    scrollingRef.current = true;
    const topPosition = element.offsetTop - HEADER_HEIGHT;
    mainElementRef.current?.scrollTo({
      top: topPosition,
      behavior: 'smooth'
    });

    // 滚动完成后重置标志
    setTimeout(() => {
      scrollingRef.current = false;
    }, 500);
  };

  const { run: handleScroll } = useThrottleFn(() => {
    if (!items.length || scrollingRef.current) return;

    const scrollPosition = mainElementRef.current?.scrollTop || 0;
    let currentKey = items[0]?._id;

    // 查找当前可见的分类
    for (const item of items) {
      const element = itemRefs.current[item._id];
      if (!element) continue;

      const elementTop = element.offsetTop - HEADER_HEIGHT;
      const elementBottom = elementTop + element.offsetHeight;

      // 当元素顶部进入视图时激活
      if (elementTop <= scrollPosition + HEADER_HEIGHT) {
        currentKey = item._id;
      }
    }

    setActiveKey(currentKey);
  }, {
    leading: true,
    trailing: true,
    wait: 100,
  });

  useEffect(() => {
    const mainElement = mainElementRef.current;
    if (!mainElement) return;

    mainElement.addEventListener('scroll', handleScroll);
    return () => mainElement.removeEventListener('scroll', handleScroll);
  }, [handleScroll, items]);

  return (
    <div style={{position:'fixed',top:'0',width:'120rem'}}>
      <div style={{ height: '120rem', backgroundColor: '#f4f4f4' }}>
        <div className='container'>
          <div className='side'>
            <SideBar
              activeKey={activeKey}
              onChange={key => {
                setActiveKey(key); // 立即更新激活状态
                const element = itemRefs.current[key];
                scrollToElement(element);
              }}
              style={{
                '--background-color': '#fff',
                '--active-background-color': '#fef0f0',
                '--active-key-border-color': '#e02e24',
                '--active-key-color': '#e02e24',
                '--item-border-radius': '0 16px 16px 0',
              }}
            >
              {items.map(item => (
                <SideBar.Item
                  key={item._id}
                  title={item.name}
                  style={{ padding: '16px 12px' }}
                />
              ))}
            </SideBar>
          </div>

          <div className='main' ref={mainElementRef} style={{marginBottom:'15rem'}}>
            {items.map(item => (
              <div key={item._id}>
                <h6
                  id={`anchor-${item._id}`}
                  ref={el => itemRefs.current[item._id] = el}
                  style={{
                    padding: '12px 0',
                    margin: '0',
                    backgroundColor: '#fff',
                    zIndex: 1,
                    boxShadow: '0 2px 4px rgba(0,0,0,0.05)'
                  }}
                >
                  {item.name}
                </h6>
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(3, 1fr)',
                  gap: '12px',
                  padding: '16px',
                  backgroundColor: '#fff',
                }} >
                  {item.subCategories.map(sub => (
                    <div
                      key={sub._id}
                      style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        padding: '8px',
                        borderRadius: '8px',
                        background: '#f8f8f8',
                        boxShadow: '0 2px 6px rgba(0,0,0,0.03)',
                        transition: 'transform 0.2s',
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.03)'}
                      onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                    >
                      <div style={{
                        width: '60px',
                        height: '60px',
                        backgroundColor: '#fef0f0',
                        borderRadius: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        marginBottom: '8px',
                        color: '#e02e24',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }} onClick={()=>{navigate(`/Lists?id=${sub._id}`)}}>
                        <img src={sub.image} style={{width:'60px',height:'60px'}} />
                      </div>
                      <h3 style={{
                        margin: '0',
                        fontSize: '12px',
                        textAlign: 'center',
                        color: '#333'
                      }}>{sub.name}</h3>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}